// Service worker for Chrome extension
chrome.runtime.onInstalled.addListener(() => {
  console.log('Extension installed');
});

// Keep service worker alive
chrome.runtime.onStartup.addListener(() => {
  console.log('Extension starting up');
});

async function saveToMongoDB({ url, data, collection }) {
  try {
    const response = await fetch('http://localhost:3000/api/save', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        url,
        collection,
        data
      })
    });
    
    const result = await response.json();
    console.log('Save result:', result);
    return { success: true, insertedId: result.insertedId };
  } catch (error) {
    console.error('API error:', error);
    return { success: false, error: error.message };
  }
}

async function extractAndSaveStore(url, autoScroll = false) {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    if (autoScroll) {
      // Keep scrolling until we reach the end
      let scrollStatus;
      do {
        scrollStatus = await chrome.tabs.sendMessage(tab.id, { action: 'scrollPage' });
        await new Promise(resolve => setTimeout(resolve, 200)); // 0.2 second delay
      } while (scrollStatus?.status !== 'Scrolled to end');
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
    
    const data = await chrome.tabs.sendMessage(tab.id, { action: 'extractFastmossStore' });
    
    const result = await saveToMongoDB({
      url: url,
      collection: 'fastmoss_store',
      data: data.result
    });
    
    return { success: result.success, result };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

/**
 * Extracts product data from the current tab and saves it to MongoDB.
 * 
 * @async
 * @function extractAndSaveProduct
 * @param {string} url - The URL of the product page to extract data from
 * @param {boolean} [autoScroll=false] - Whether to auto-scroll the page before extraction
 * @returns {Promise<Object>} Result object with success status and either saved data or error
 * @throws {Error} If extraction or saving fails
 */
async function extractAndSaveProduct(url, autoScroll = false) {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    if (autoScroll) {
      // Keep scrolling until we reach the end
      let scrollStatus;
      do {
        scrollStatus = await chrome.tabs.sendMessage(tab.id, { action: 'scrollPage' });
        await new Promise(resolve => setTimeout(resolve, 200)); // 0.2 second delay
      } while (scrollStatus?.status !== 'Scrolled to end');
      await new Promise(resolve => setTimeout(resolve, 5000));
    }
    
    const data = await chrome.tabs.sendMessage(tab.id, { action: 'extractFastmossProduct' });
    
    const result = await saveToMongoDB({
      url: url,
      collection: 'fastmoss_product',
      data: data.result
    });
    
    return { success: result.success, result };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

async function extractAndSaveProductSearchResult(url, fetchAllPages = false) {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

  let allResults = [];
  if (fetchAllPages) {
    // Keep scrolling until we reach the end
    let switchPageResult;
    while (true) {
      const data = await chrome.tabs.sendMessage(tab.id, { action: 'extractProductSearchResult' });
      allResults = allResults.concat(data.result);
      switchPageResult = await chrome.tabs.sendMessage(tab.id, { action: 'switchPage' });
      if (switchPageResult?.status === 'Switched to end') {
        break;
      }
      await new Promise(resolve => setTimeout(resolve, 5000)); // 0.2 second delay
    }
  } else {
      const data = await chrome.tabs.sendMessage(tab.id, { action: 'extractProductSearchResult' });
      allResults = data.result;
  }
  
  // Save each record individually
  const results = [];
  for (const record of allResults) {
    const result = await saveToMongoDB({
      url: url,
      collection: 'fastmoss_product_search_result',
      data: record
    });
    results.push(result);
  }
  return results;
}

async function getAndOpenCurrentPageSearchResults() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  
  // Get all search result links from content script
  const links = await chrome.tabs.sendMessage(tab.id, { 
    action: 'getAllSearchResultsLink' 
  });

  // Open each link in new tab with delay
  for (const link of links) {
    await chrome.tabs.create({ url: link, active: false });
    await new Promise(resolve => setTimeout(resolve, 1000)); // 1 second delay
  }
}

async function extractAndSaveOpenProducts(url, autoScroll = false) {
  const tabs = await chrome.tabs.query({
    url: 'https://www.fastmoss.com/zh/e-commerce/detail/*'
  });
  
  const results = [];
  for (const tab of tabs) {
    // Activate the tab
    await chrome.tabs.update(tab.id, { active: true });
    
    // Call extractAndSaveProduct directly
    const result = await extractAndSaveProduct(url, autoScroll);
    
    results.push({
      tabId: tab.id,
      success: result.success,
      result: result.result
    });

    // Close the tab after successful extraction
    if (result.success) {
      await chrome.tabs.remove(tab.id);
    }
  }
  return results;
}

// Message handler
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'saveToMongoDB') {
    (async () => {
      try {
        const result = await saveToMongoDB(request);
        sendResponse({ success: result.success, result });
      } catch (error) {
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }
  else if (request.action === 'extractAndSaveStore') {
    (async () => {
      const result = await extractAndSaveStore(request.url, request.autoScroll);
      sendResponse(result);
    })();
    return true;
  }
  else if (request.action === 'extractAndSaveAllStores') {
    (async () => {
      try {
        const tabs = await chrome.tabs.query({ 
          url: 'https://www.fastmoss.com/zh/shop-marketing/detail/*'
        });
        
        const results = [];
        for (const tab of tabs) {
          // Activate the tab
          await chrome.tabs.update(tab.id, { active: true });
          
          // Call extractAndSaveStore directly
          const result = await extractAndSaveStore(request.url, request.autoScroll);
          
          results.push({
            tabId: tab.id,
            success: result.success,
            result: result.result
          });
        }
        console.log('extractAndSaveAllStores Results:', results);
        sendResponse({ success: true, results });
      } catch (error) {
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }
  else if (request.action === 'extractAndSaveProduct') {
    (async () => {
      const result = await extractAndSaveProduct(request.url, request.autoScroll);
      sendResponse(result);
    })();
    return true;
  }
  else if (request.action === 'extractAndSaveAllProducts') {
    (async () => {
      try {
        results = await extractAndSaveOpenProducts(request.url, request.autoScroll);
        console.log('extractAndSaveAllProducts Results:', results);
        sendResponse({ success: true, results });
      } catch (error) {
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }
  else if (request.action === 'openAllSearchResults') {
    (async () => {
      try {
        await getAndOpenCurrentPageSearchResults();

        sendResponse({ success: true });
      } catch (error) {
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }
  else if (request.action === 'extractAndSaveProductSearchResult') {
    (async () => {
      try {
        const results = await extractAndSaveProductSearchResult(request.url, request.fetchAllPages);
        
        sendResponse({ success: true, result: results });
      } catch (error) {
        console.log('extractAndSaveProductSearchResult Error:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }
  else if (request.action === 'extractAllFastmossProductsFromList') {
    (async () => {
      try {
        // Always start from list page
        const [start_tab] = await chrome.tabs.query({ active: true });
        const startUrl = start_tab.url.split('?')[0];
        let allResults = [];
        while (true) {
          await getAndOpenCurrentPageSearchResults();
          const results = await extractAndSaveOpenProducts(request.url, request.autoScroll);
          allResults = allResults.concat(results);
          const tabs = await chrome.tabs.query({ url: startUrl + '*' });
          const tab = tabs[0];
          await chrome.tabs.update(tab.id, { active: true });
          const switchPageResult = await chrome.tabs.sendMessage(tab.id, { action: 'switchPage' });
          if (switchPageResult?.status === 'Switched to end') {
            break;
          }
          await new Promise(resolve => setTimeout(resolve, 5000));
        }
        
        sendResponse({ success: true, result: allResults });
      } catch (error) {
        console.log('extractAllFastmossProductsFromList Error:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }
});
